import Mock from 'mockjs'
import { localStore, sessionStore } from '@/common/utils/storage.js'
import _ from 'lodash'

const Random = Mock.Random

const add = (data) => {
  let userOrder = localStore.get('tiny_order')
  userOrder = userOrder || []

  const order = {
    orderId: Random.guid(),
    orderNo: Random.id(),
    products: data.products,
    contact: data.contact,
    total: _.sumBy(data.products, prod => prod.price * prod.count),
    count: _.sumBy(data.products, prod => prod.count),
    status: 'NO_PAY',
    statusCn: '等待付款'
  }

  userOrder.unshift(order)
  localStore.set('tiny_order', userOrder)

  return order.orderId
}

const submit = (data) => {
  return add(data)
}

const get = (orderId) => {
  const userOrder = localStore.get('tiny_order')

  if (userOrder && userOrder.length) {
    const orderResult = _.find(userOrder, (order) => {
      return order.orderId === orderId
    })
    return orderResult || {}
  } else {
    return null
  }
}

const list = () => {
  return localStore.get('tiny_order') || []
}

const setPreviewOrder = (products) => {
  if (products && products.length) {
    const preview = {
      products: products,
      total: _.sumBy(products, prod => prod.price * prod.count),
      count: _.sumBy(products, prod => prod.count)
    }

    sessionStore.set('previewOrder', preview)
    return {}
  } else {
    return null
  }
}

const getPreviewOrder = () => {
  return sessionStore.get('previewOrder')
}

export default {
  add,
  submit,
  get,
  list,
  setPreviewOrder,
  getPreviewOrder
}
